package com.ruoyi.beforehand.controller;


import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.attachment.domain.Attachment;
import com.ruoyi.attachment.service.IAttachmentService;
import com.ruoyi.beforehand.domain.*;
import com.ruoyi.beforehand.service.IInfoBeforehandEvaluateDetailService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.evaluate.infoprojectevaluate.domain.InfoProjectEvaluate;
import com.ruoyi.system.service.ISysDeptService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.beforehand.service.IInfoBeforehandEvaluateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 事前评估信息Controller
 *
 * @author ruoyi
 * @date 2022-02-24
 */
@RestController
@RequestMapping("/beforehand/evaluate")
@Api(tags = "事前评估信息")
public class InfoBeforehandEvaluateController extends BaseController
{
    @Autowired
    private IInfoBeforehandEvaluateService infoBeforehandEvaluateService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IInfoBeforehandEvaluateDetailService iInfoBeforehandEvaluateDetailService;
    private IAttachmentService attachmentService;
    /**
     * 查询事前评估信息列表
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:list')")
    @GetMapping("/list")
    @ApiOperation("查询事前评估信息列表")
    @ApiImplicitParam(name = "infoBeforehandEvaluate", value = "实体类", dataType = "InfoBeforehandEvaluate")
    public TableDataInfo list(InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        startPage();
        List<InfoBeforehandEvaluate> list = infoBeforehandEvaluateService.selectInfoBeforehandEvaluateList(infoBeforehandEvaluate);
        return getDataTable(list);
    }

    /**
     * 导出事前评估信息列表
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:export')")
    @Log(title = "事前评估信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        List<InfoBeforehandEvaluate> list = infoBeforehandEvaluateService.selectInfoBeforehandEvaluateList(infoBeforehandEvaluate);
        ExcelUtil<InfoBeforehandEvaluate> util = new ExcelUtil<InfoBeforehandEvaluate>(InfoBeforehandEvaluate.class);
        util.exportExcel(response, list, "事前评估信息数据");
    }

    /**
     * 获取事前评估信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取事前评估信息详细信息")
    @ApiImplicitParam(name = "id", value = "id", dataType = "InfoBeLongforehandEvaluate")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(infoBeforehandEvaluateService.selectInfoBeforehandEvaluateById(id));
    }

    /**
     * 新增事前评估信息
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:add')")
    @Log(title = "事前评估信息", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增事前评估信息")
    @ApiImplicitParam(name = "infoBeforehandEvaluate", value = "实体类", dataType = "InfoBeforehandEvaluate")
    public AjaxResult add(@RequestBody InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        return toAjax(infoBeforehandEvaluateService.insertInfoBeforehandEvaluate(infoBeforehandEvaluate));
    }

    /**
     * 修改事前评估信息
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:edit')")
    @Log(title = "事前评估信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改事前评估信息")
    @ApiImplicitParam(name = "infoBeforehandEvaluate", value = "实体类", dataType = "InfoBeforehandEvaluate")
    public AjaxResult edit(@RequestBody InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        return toAjax(infoBeforehandEvaluateService.updateInfoBeforehandEvaluate(infoBeforehandEvaluate));
    }

    /**
     * 删除事前评估信息
     */
    @PreAuthorize("@ss.hasPermi('beforehand:evaluate:remove')")
    @Log(title = "事前评估信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除事前评估信息")
    @ApiImplicitParam(name = "ids", value = "实体类", dataType = "Long[]")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(infoBeforehandEvaluateService.deleteInfoBeforehandEvaluateByIds(ids));
    }

    /**
     * 下达 填报 审核
     * 待填报1
     * 已填报2
     * 待审核3
     * 已审核4（通过）
     * 驳回5
     */
    //@PreAuthorize("@ss.hasPermi('beforehand:evaluate:report')")
    @RequestMapping(value = "/order", method = RequestMethod.POST)
    @ApiOperation("下达,填报，审核")
    @ApiImplicitParam(name = "infoBeforehandEvaluate", value = "实体类", dataType = "InfoBeforehandEvaluate")
    public AjaxResult order(@RequestBody InfoBeforehandEvaluate infoBeforehandEvaluate){
        return toAjax(infoBeforehandEvaluateService.updateInfoBeforehandEvaluate(infoBeforehandEvaluate));
    }

    /**
     * 将自评表里的信息插入详情表里
     * @param infoScoreVo
     * @return
     */
    @RequestMapping(value = "/score", method = RequestMethod.POST)
    public TableDataInfo score(@RequestBody InfoScoreVo infoScoreVo){
        List<InfoBeforehandEvaluateDetail> list= iInfoBeforehandEvaluateDetailService.updateInfoBeforehandEvaluateDetails(infoScoreVo);
        return getDataTable(list);
    }


    /**
     * 查插入列表信息
     * @param infoScoreVo
     * @return
     */
    @RequestMapping(value = "/index",method = RequestMethod.POST)
    public TableDataInfo idnex(@RequestBody InfoScoreVo infoScoreVo){
        List<InfoBeforehandEvaluateDetail> infoBeforehandEvaluateDetail=iInfoBeforehandEvaluateDetailService.selectInfoBeforehandEvaluateDetailByIds(infoScoreVo.getBeforehandId());
        return getDataTable(infoBeforehandEvaluateDetail);
    }




    /**
     * 修改分数
     */
    @RequestMapping(value = "/updateScore",method = RequestMethod.POST)
    public AjaxResult updateScore(@RequestBody InfoScoreVo infoScoreVo){
        return toAjax(infoBeforehandEvaluateService.updateInfoBeforehandEvaluatess(infoScoreVo));
    }


    /**
     * 下载事前绩效评估指标及评分表
     */
    @PostMapping("/downloads/{id}")
    @ResponseBody
    @ApiOperation("下载事前绩效评估指标及评分表")
    @ApiImplicitParam(name = "id", value = "编号", dataType = "Long")
    public AjaxResult downloads(@PathVariable("id") Long id) {
        String fileName = null;
        Long ids= 0L;
        ids= id;
//        InfoAllVo infoAllVo=new InfoAllVo();
//        List<InfoAllVo> inn=new ArrayList<>();
        /**
         * 根据id查表里的数据
         */
        InfoBeforehandEvaluate infoBeforehandEvaluate=infoBeforehandEvaluateService.selectInfoBeforehandEvaluateById(id);
        /**
         * deptId部门编号获取自评表里的部门编号
         */
        Long deptId = infoBeforehandEvaluate.getDeptId();

        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoBeforehandEvaluate.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("sq.ftl", "utf-8");
            /**
             * 把查到的东西放进map中
             */
            Map<String, Object> data = new HashMap<>();

            /**
             * 查询部门信息
             */
            SysDept dept = deptService.selectDeptsById(deptId);
            //dept.getParentName() +m
            String title = dept.getDeptName() + "事前绩效评估指标及评分表";
            fileName = title;

            /**
             * map里放的东西
             */
            data.put("fileName", title);
            data.put("ids", ids);
            data.put("infoBeforehandEvaluate", infoBeforehandEvaluate);

            /**
             * 查询对应信息
             */
            List<InfoBeforehandEvaluateDetail> infoBeforehandEvaluateDetails = iInfoBeforehandEvaluateDetailService.selectInfoBeforehandEvaluateDetailsById(infoBeforehandEvaluate.getId());
            //总分
            int YjZongfen = 0;
            int EjZongfen = 0;
            int SjZongfen = 0;


            for (int i = 0; i < infoBeforehandEvaluateDetails.size(); i++) {
                InfoBeforehandEvaluateDetail infoBeforehandEvaluateDetail = infoBeforehandEvaluateDetails.get(i);

                /**
                 *  判断指标值是否不为空
                 */
                if (StringUtils.isNotBlank(infoBeforehandEvaluateDetail.getTargetOneScore())||StringUtils.isNotBlank(infoBeforehandEvaluateDetail.getTargetTwoScore())||StringUtils.isNotBlank(String.valueOf(infoBeforehandEvaluateDetail.getScore()))) {

                    /**
                     * 累加
                     */
                    if(!org.springframework.util.StringUtils.isEmpty(infoBeforehandEvaluateDetail.getTargetOneScore())){
                        YjZongfen += Integer.parseInt(infoBeforehandEvaluateDetail.getTargetOneScore());
                    }
                    if(!org.springframework.util.StringUtils.isEmpty(infoBeforehandEvaluateDetail.getTargetTwoScore())){
                        EjZongfen += Integer.parseInt(infoBeforehandEvaluateDetail.getTargetTwoScore());
                    }
                    if(!org.springframework.util.StringUtils.isEmpty(infoBeforehandEvaluateDetail.getScore())){
                        SjZongfen += Integer.parseInt(String.valueOf(infoBeforehandEvaluateDetail.getScore()));
                    }
                }
            }
            //分数
            infoBeforehandEvaluate.setYjZongFen(YjZongfen + "");
            infoBeforehandEvaluate.setEjZongFen(EjZongfen + "");
            infoBeforehandEvaluate.setSjZongFen(SjZongfen + "");
            data.put("infoBeforehandEvaluateDetails", infoBeforehandEvaluateDetails);
//            data.put("infoBeforehandEvaluate", infoBeforehandEvaluate);
//            infoAllVo.setInfoBeforehandEvaluate(infoBeforehandEvaluate);
//            infoAllVo.setInfoBeforehandEvaluateDetail(infoBeforehandEvaluateDetails);
//            infoAllVo.setId(ids);
            Writer out = null;

            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + ".doc");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);


//            ByteArrayOutputStream baos = new ByteArrayOutputStream();

//            infoAllVo.setUrl1(downloadPath+".doc");
//            infoAllVo.setFileName(fileName+".doc");
//            inn.add(infoAllVo);
            out.close();

            System.out.println("................word文档生成成功 !.............");
            return AjaxResult.success((fileName+".doc"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

        return AjaxResult.error();

    }

    /**
     * 下载事前绩效评估指标及评分表
     */
    @PostMapping("/download/{id}")
    @ResponseBody
    @ApiOperation("下载事前绩效评估报告")
    @ApiImplicitParam(name = "id", value = "编号", dataType = "Long")
    public AjaxResult download(@PathVariable("id") Long id) {
        /**
         * 根据id查表里的数据
         */
        InfoBeforehandEvaluate infoBeforehandEvaluate=infoBeforehandEvaluateService.selectInfoBeforehandEvaluateById(id);
        /**
         * deptId部门编号获取自评表里的部门编号
         */
        Long deptId = infoBeforehandEvaluate.getDepartmentId();
        String fileName = "";
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoBeforehandEvaluate.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("sqbg.ftl", "utf-8");
            /**
             * 把查到的东西放进map中
             */
            Map<String, Object> data = new HashMap<>();
            /**
             * 查询部门信息
             */
            SysDept dept = deptService.selectDeptsById(deptId);
            //年度获取时间
            String title = dept.getDeptName() + "事前绩效评估报告";
            fileName=title;
            /**
             * map里放的东西
             */
            data.put("fileName", title);
            data.put("infoBeforehandEvaluate", infoBeforehandEvaluate);
            data.put("dept",dept);
            Writer out = null;
            String downloadPath = RuoYiConfig.getDownloadPath()+ fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + ".doc");
            infoBeforehandEvaluate.setReportUrl(String.valueOf(outFile));
            infoBeforehandEvaluateService.updateInfoBeforehandEvaluates(infoBeforehandEvaluate);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
            return AjaxResult.success((fileName+".doc"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }
    /**
     * 查询事前评估审核信息列表
     */
    @GetMapping("/shlist")
    public TableDataInfo shlist(InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        startPage();
        List<InfoBeforehandEvaluate> list = infoBeforehandEvaluateService.selectInfoBeforehandEvaluateLists(infoBeforehandEvaluate);
        return getDataTable(list);
    }
    /**
     * 查询事前评估填报信息列表
     */
    @GetMapping("/tblist")
    public TableDataInfo tblist(InfoBeforehandEvaluate infoBeforehandEvaluate)
    {
        startPage();
        List<InfoBeforehandEvaluate> list = infoBeforehandEvaluateService.selectInfoBeforehandEvaluateListss(infoBeforehandEvaluate);
        return getDataTable(list);
    }

    /**
     * 上传文件
     */
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public AjaxResult uploadFiles(@RequestBody InfoBeforehandEvaluate infoBeforehandEvaluate) {
        return toAjax(infoBeforehandEvaluateService.uploadFiles(infoBeforehandEvaluate));
    }

    /**
     * 上传多文件（type:1,整体附件上传）
     */
    @ApiOperation("上传附件")
    @RequestMapping(value = "/uploadMuchFiles", method = RequestMethod.POST)
    public AjaxResult uploadMuchFiles(@RequestBody Attachment attachment) {
        return toAjax(infoBeforehandEvaluateService.uploadMuchFiles(attachment,1));
    }
    /**
     * 根据路径删除
     */
    @ApiOperation("删除文件")
    @RequestMapping(value = "/deleteAttachmentFileByPath", method = RequestMethod.DELETE)
    public AjaxResult deleteFileByPath(@RequestBody Attachment attachment) {
        //文件路径
        String filePath = attachment.getAttachmentUrl();
        //id
        Long attachmentId = attachment.getAttachmentId();
        if (StringUtils.isNotEmpty(filePath)) {
            //基础文件夹
            String baseFilePath = RuoYiConfig.getUploadPath();
            String filePath1 = baseFilePath + filePath.replace("/profile/upload","");
            File file = new File(filePath1);
            if (file.exists()) {
                //删除
                boolean delete = file.delete();
                if (delete) {
                    //删除成功则删除数据库
                    infoBeforehandEvaluateService.deleteAttachmentByAttachmentId(attachmentId);
                    return AjaxResult.success("删除成功");
                } else {
                    return AjaxResult.error("删除失败");
                }
            } else {
                //文件不存在
                return AjaxResult.error("删除失败，文件不存在");
            }
        }
        return AjaxResult.error("删除失败，文件路径为空");
    }

    /**
     * 事前评估指标上传佐证(type:2,指标佐证上传)
     */
    @ApiOperation("事前评估指标上传佐证")
    @PostMapping("beforehandFile")
    public AjaxResult beforehandFile(@RequestBody Attachment attachment) {
        return toAjax(infoBeforehandEvaluateService.uploadMuchFiles(attachment,2));
    }
}
